<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Merch as MerchModel;
use app\user\model\User as UserModel;
use util\Tree;
use think\facade\Db;

/**
 * 商户默认控制器
 * @package app\mall\admin
 */
class Merch extends Admin
{
    /**
     * 商户首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
		$map[] = ['trash', '=', 0];
		$order = $this->getOrder('sort,id desc');
        // 数据列表
        $data_list = MerchModel::where($map)->order($order)->paginate(config('paginate'));
		
		foreach ($data_list as $key => $value){
			// $data_list[$key]['order'] = '订单管理';
			// $data_list[$key]['charges'] = '统计报表';
		}
		// 回收站按钮
		$btnRe = [
		    'class' => 'btn btn-default',
		    'icon'  => 'fa fa-fw fa-recycle',
		    'title' => '回收站',
			'href'  => url('mall/recycle/index')
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('商户管理') // 设置页面标题
            ->setSearch(['id' => 'ID', 'merch_name' => '商户名', 'nickname' => '管理员', 'short_name' => '商户简称']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['short_name', '商户名'],
				['wxpay_id', '商户号'],
				// ['order', '订单', 'link', url('mall/order/index', ['pid'=>'__id__'])],
				// ['charges', '统计', 'link', url('mall/counts/daily', ['pid'=>'__id__'])],
                ['create_time', '创建时间', 'date'],
				['update_time', '更新时间', 'date'],
                ['status', '状态', 'switch'],
				['sort', '排序', 'text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
			->addTopButton('custom', $btnRe) // 回收站
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
			->setColumnWidth(['id' => 60,'cid' => 80, 'order' => 80, 'charges' => 80])
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Merch');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if ($merch = MerchModel::create($data)) {
                // 记录行为
                action_log('merch_add', 'merch_merch',$merch->id, UID, $data['short_name']);
				cache('merch_column', null);
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增商户') // 设置页面标题
			->addGroup([
				'基本信息' =>[
					['text:8', 'merch_name', '商户名', '<span class="text-danger">必填</span>，商户全称'],
					['text:8', 'short_name', '商户简称', '<span class="text-danger">必填</span>，商户简称'],
					// ['tags:8', 'uids', '管理人员ID', '前端会员ID， 以英文逗号<code> , </code>分开'],
					['text:8', 'sort', '排序', '', '100'],
					['radio', 'status', '状态', '', ['禁用', '启用'], 1]
				],
				'支付信息' =>[
					['text:8', 'wxpay_id', '微信商户号', '微信支付申请分配的商户ID'],
					['text:8', 'wx_rate', '微信支付费率', '微信支付费率百分比','', ['', '<i class="fa fa-fw fa-percent"></i>']],
					['text:8', 'api_key', 'ApiV3秘钥', '微信支付API秘钥，V3版本'],
					['text:8', 'serialno', '证书序列号', '微信支付证书序列号'],
				],
			])
			->layout(['cid' => 8, 'title' => 8,  'mobile' => 8, 'code' => 8, 'uid' => 8])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 商户id
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
		// 获取数据
		$info = MerchModel::where('id', $id)->find();
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Merch');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
			
            if (MerchModel::update($data)) {
                // 记录行为
                action_log('merch_edit', 'merch_merch', $id, UID, $data['short_name']);
				cache('merch_column', null);
				cache('merch_info_'.$id, null);
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }
		// 使用ZBuilder快速创建表单
		return ZBuilder::make('form')
			->setPageTitle('编辑商户') // 设置页面标题
			->addGroup([
				'基本信息' =>[
					['hidden', 'id'],
					['text:8', 'merch_name', '商户名', '<span class="text-danger">必填</span>，商户全称'],
					['text:8', 'short_name', '商户简称', '<span class="text-danger">必填</span>，商户简称'],
					// ['tags:8', 'uids', '管理人员ID', '前端会员ID， 以英文逗号<code> , </code>分开'],
					['text:8', 'sort', '排序', '',],
					['radio', 'status', '状态', '', ['禁用', '启用']]
				],
				'支付信息' =>[
					['text:8', 'wxpay_id', '微信商户号', '<span class="text-danger">必填</span>，微信支付申请分配的商户ID'],
					['text:8', 'wx_rate', '微信支付费率', '微信支付费率百分比','', ['', '<i class="fa fa-fw fa-percent"></i>']],
					['text:8', 'api_key', 'ApiV3秘钥', '微信支付API秘钥，V3版本'],
					['text:8', 'serialno', '证书序列号', '微信支付证书序列号'],
					['file', 'privatekey', '微信支付证书私钥', 'apiclient_key.pem', '', '100', 'pem',  '', '', 'local', 'local'],
					['file', 'publickey', '微信支付证书公钥', 'apiclient_cert.pem', '', '100', 'pem',  '', '', 'local', 'local'],
				],
			])
			->layout(['cid' => 8, 'title' => 8,  'mobile' => 8, 'code' => 8, 'uid' => 8])
			->setFormData($info) // 设置表单数据
			->fetch();
    }

    /**
     * 删除商户
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
    	
        // 移动到回收站
        if (false === MerchModel::where('id', 'in', $ids)->update(['trash' => 1])) {
            $this->error('删除失败');
        }
		// 清除缓存
    	cache('merch_list', null);
		cache('merch_column', null);
		
		if (is_array($ids)) {
			foreach ($ids as $id){
				cache('merch_info_'.$id, null);
			}
		} else {
			cache('merch_info_'.$ids, null);
		}
		
    	$merch_id    = is_array($ids) ? '' : $ids;
    	$titles = MerchModel::where('id', 'in', $ids)->column('short_name');
        // 删除并记录日志
        action_log('merch_trash', 'mall_merch', $merch_id, UID, implode('、', $titles));
        $this->success('删除成功');
    }

    /**
     * 启用商户
     * @param array $ids 商户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用商户
     * @param array $ids 商户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置商户状态：禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        switch ($type) {
            case 'enable':
                if (false === MerchModel::where('id', 'in', $ids)->update(['status' => 1])) {
                    $this->error('启用失败');
                }
                break;
            case 'disable':
                if (false === MerchModel::where('id', 'in', $ids)->update(['status' => 0])) {
                    $this->error('禁用失败');
                }
                break;
            case 'delete':
                if (false === MerchModel::where('id', 'in', $ids)->update(['trash' => 1])) {
                    $this->error('删除失败');
                }
				$type = 'trash';
                break;
            default:
                $this->error('非法操作');
        }
		foreach ($ids as $id){
			cache('merch_info_'.$id, null);
		}
        action_log('merch_'.$type, 'mall_merch', '', UID);
		cache('merch_column', null);
        $this->success('操作成功');
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = MerchModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
		cache('merch_column', null);
		cache('merch_info_'.$id, null);
        return parent::quickEdit(['merch_edit', 'mall_merch', $id, UID, $details]);
    }
}
